package com.station.Activitys.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.seek.biscuit.Biscuit;
import com.seek.biscuit.CompressResult;
import com.seek.biscuit.OnCompressCompletedListener;
import com.station.Activitys.R;
import com.station.Activitys.activity.base.BaseActivity;
import com.station.Activitys.adapter.ImageDisplayMagAdapter;
import com.station.Activitys.adapter.ImageMagAdapter;
import com.station.Activitys.bean.ImageJson;
import com.station.Activitys.bean.ImageMag;
import com.station.Activitys.bean.Linkage;
import com.station.Activitys.bean.MyTest;
import com.station.Activitys.bean.State;
import com.station.Activitys.http.manager.WorkManager;
import com.station.Activitys.utils.CacheManger;
import com.station.Activitys.utils.Constant;
import com.station.Activitys.utils.DialogUtils;
import com.station.Activitys.utils.NetUtils;
import com.station.Activitys.utils.StringUtils;
import com.station.Activitys.utils.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhy.autolayout.AutoLinearLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：基站管理平台 手机app
 * 类描述：我的可验收信息 提交验收 页面
 * 创建人：张飞祥
 * 创建时间：2018/10/17 14:15
 * 修改人：张飞祥
 * 修改时间：2018/10/17 14:15
 * 修改备注：
 */
public class MyTestMsgSubmitActivity extends BaseActivity implements MaterialSpinner.OnItemSelectedListener{

    //TODO 标题
    //返回按钮
    @Bind(R.id.iv_return) ImageView ivReturn;
    //标题
    @Bind(R.id.tv_title) TextView tvTitle;

    //TODO 基站 基础信息
    //基站名称
    @Bind(R.id.tv_name) TextView tvName;
    //基站状态
    @Bind(R.id.tv_state) TextView tvState;
    //自动获取的经纬度
    @Bind(R.id.tv_gps) TextView tvGps;
    //手动输入的经度
    @Bind(R.id.et_my_gps_x) EditText etMyGpsX;
    //手动输入的纬度
    @Bind(R.id.et_my_gps_y) EditText etMyGpsY;
    //信号强度
    @Bind(R.id.tv_signal) TextView tvSignal;
    //省份
    @Bind(R.id.sp_province)  MaterialSpinner spProvince;
    //城市
    @Bind(R.id.sp_city) MaterialSpinner spCity;
    //网格
    @Bind(R.id.sp_grid) MaterialSpinner spGrid;
    //厂家
    @Bind(R.id.sp_vender) MaterialSpinner spVender;
    //物理站址名称
    @Bind(R.id.et_physical_name) EditText etPhysicalName;
    //物理站址地址
    @Bind(R.id.et_physical_address) EditText etPhysicalAddress;
    //区域类型
    @Bind(R.id.sp_area_type) MaterialSpinner spAreaType;
    //主场景类型
    @Bind(R.id.sp_main_scene_type) MaterialSpinner spMainSceneType;
    //站型
    @Bind(R.id.sp_station_model) MaterialSpinner spStationModel;
    //优先级
    @Bind(R.id.sp_priority) MaterialSpinner spPriority;
    //工程期属
    @Bind(R.id.sp_project_num) MaterialSpinner spProjectNum;

    //TODO 工单信息
    //总布局
    @Bind(R.id.layout_survey_msg) AutoLinearLayout layoutSurveyMsg;
    //反填图片列表
    @Bind(R.id.rv_http_img_list) RecyclerView rvHttpImgList;
    //新增图片列表
    @Bind(R.id.rv_img_list) RecyclerView rvImgList;

    /**
     * 变量
     */
    //初始化网络请求
    public WorkManager mApiManager;
    //TODO 实体类
    //工单 实体类
    private MyTest mMyTest = null;

    //TODO 上传图片 变量
    //图片反填数据适配器
    private ImageDisplayMagAdapter mHttpAdapter = null;
    //上传图片适配器
    private ImageMagAdapter mUploadAdapter = null;
    //数据源
    private List<ImageMag> mImageList = new ArrayList<>();
    //当前 那个操作上传图片 的 pos
    private int mPos;


    //TODO 下拉列表
    //省
    private List<String> mProvinceList = new ArrayList<>();
    private String mProvinceStr = "";
    private List<Linkage> mLinkageList = null;
    private Linkage mProvince = null;
    //市
    private List<String> mCityList = new ArrayList<>();
    private String mCityStr = "";
    private List<Linkage> mLinkageCityList = null;
    private Linkage mCity = null;
    //区
    private List<String> mGridList = new ArrayList<>();
    private List<Linkage> mLinkageGridList = null;
    private String mGridStr = "";
    //站型
    private List<String> mModelList = null;
    private String mModel = "";
    //厂家
    private List<String> mVenderList = null;
    private String mVender = "";
    //区域类型
    private List<String> mAreaTypeList = null;
    private String mAreaType = "";
    //主场景类型
    private List<String> mMainSceneTypeList = null;
    private String mMainSceneType = "";
    //工程期属
    private List<String> mProjectNumList = null;
    private String mProjectNum = "";
    //优先级
    private List<String> mPriorityList = null;
    private String mPriority = "";


    //TODO 当前手机信号
    //TelephonyManager类的对象
    private TelephonyManager mTel = null;
    //MyPhoneStateListener类的对象，即设置一个监听器对象
    private MyPhoneStateListener mMyListener = null;
    //运营商名称
    private String mOperator;
    //信号强度
    private int mDbmNumber;

    //TODO 高德地图
    //声明 高德地图 AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明 高德地图 AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    //自动获取的 经度
    private double mGpsX;
    //自动获取的 纬度
    private double mGpsY;

    @Override
    protected void initUI() {
        setContentView(R.layout.act_my_test_msg_submit);
        //网络请求接口 常驻方法
        mApiManager = mApiManager.getWorkApiManager(this, this.getTaskId());


        //TODO 初始化运营商信息
        //初始化对象
        mMyListener = new MyPhoneStateListener();
        //Return the handle to a system-level service by name.通过名字获得一个系统级服务
        mTel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //Registers a listener object to receive notification of changes in specified telephony states.设置监听器监听特定事件的状态
        mTel.listen(mMyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        //获取当前运营商
        mOperator = NetUtils.getYYS(getApplicationContext());

        //初始化定位
        initLocation();
    }

    @Override
    protected void initData() {

        //获取从上个页面 传递过来的 实体类
        Bundle bundle = this.getIntent().getExtras();
        //获取 实体类
        mMyTest = (MyTest) bundle.getSerializable(Constant.INTENT_MY_TEST_BEAN);
        //获取当前用户
        mUser = CacheManger.getUser(mACache);
        //解决 滑动冲突
        rvHttpImgList.setNestedScrollingEnabled(false);
        rvImgList.setNestedScrollingEnabled(false);

        //设置标题
        tvTitle.setText("验收");
        //显示返回按钮
        ivReturn.setVisibility(View.VISIBLE);

        //TODO 填充基础数据
        setBasicsData();
        //TODO 选择事件（全部）
        setItemOnClickAll();
    }

    /**
     * 填充基础数据
     */
    private void setBasicsData() {
        /**
         * 填充 数据
         */
        if (mMyTest != null) {
            //TODO 开始网络请求获取图片 数据
            initShowTimeDialog("正在加载数据，请稍后....", this);
            mApiManager.workMyTestMsgImages(mMyTest.getId());

            //基站名称
            tvName.setText(mMyTest.getNameOfOpenStationAddr());
            //基站状态
            tvState.setText(mMyTest.getState());
            //物理站址名称
            etPhysicalName.setText(mMyTest.getPhysicalStationName());
            //物理站址地址
            etPhysicalAddress.setText(mMyTest.getAddressOfPhysicalStation());
            //手动输入的经度
            etMyGpsX.setText(mMyTest.getManualInputGpsX());
            //手动输入的纬度
            etMyGpsY.setText(mMyTest.getManualInputGpsY());
            //初始化 下拉列表数据
            setSelectData();

            //TODO 图片新建上传列表
            mUploadAdapter = new ImageMagAdapter(MyTestMsgSubmitActivity.this, mImageList) {
                @Override
                public void setImageUploadPos(int position) {
                    mPos = position;
                }
            };
            //添加 适配器 样式
            rvImgList.setLayoutManager(new LinearLayoutManager(MyTestMsgSubmitActivity.this, LinearLayoutManager.VERTICAL, false));
            //添加 适配器
            rvImgList.setAdapter(mUploadAdapter);
            //添加动画
            rvImgList.setItemAnimator(new DefaultItemAnimator());
            //解决 滑动冲突
            rvImgList.setNestedScrollingEnabled(false);
        }
    }

    /**
     * 初始化 下拉列表数据
     */
    private void setSelectData(){
        //TODO 从内存中 获取 当前列表集合 并填充到列表中
        //TODO 三级联动
        //省
        mLinkageList = CacheManger.getLinkage(mACache, Constant.CACHE_LINKAGE);
        if (mLinkageList != null) {
            //循环获取name
            for (Linkage province : mLinkageList){
                mProvinceList.add(province.getName());
            }
            spProvince.setItems(mProvinceList);
            //设置 默认值
            mProvinceStr = mProvinceList.get(0);
            //设置 列表默认选中值
            spProvince.setSelectedIndex(0);
            //设置 省级选择的 子数据 实体
            mProvince = mLinkageList.get(0);
            //反填默认值
            for (int i = 0;i<mProvinceList.size();i++){
                String name = mProvinceList.get(i);
                if (mMyTest.getProvince()!=null && name.equals(mMyTest.getProvince())){
                    //设置 默认值
                    mProvinceStr = name;
                    //设置 列表默认选中值
                    spProvince.setSelectedIndex(i);
                    //设置 省级选择的 子数据 实体
                    mProvince = mLinkageList.get(i);
                }
            }
        }

        //市
        if (mProvince.getChildrenNodes() != null) {
            mLinkageCityList = mProvince.getChildrenNodes();
            //循环获取name
            for (Linkage province : mLinkageCityList){
                mCityList.add(province.getName());
            }
            //数据填充
            spCity.setItems(mCityList);
            //设置 默认值
            mCityStr = mCityList.get(0);
            //设置 列表默认选中值
            spCity.setSelectedIndex(0);
            //设置 省级选择的 子数据 实体
            mCity = mLinkageCityList.get(0);
            //反填默认值
            for (int i = 0;i<mCityList.size();i++){
                String name = mCityList.get(i);
                if (mMyTest.getLocalNetworkAddress()!=null && name.equals(mMyTest.getLocalNetworkAddress())){
                    //设置 默认值
                    mCityStr = name;
                    //设置 列表默认选中值
                    spCity.setSelectedIndex(i);
                    //设置 省级选择的 子数据 实体
                    mCity = mLinkageCityList.get(i);
                }
            }
        }

        //区
        if (mCity.getChildrenNodes() != null) {
            mLinkageGridList = mCity.getChildrenNodes();
            //循环获取name
            for (Linkage province : mLinkageGridList){
                mGridList.add(province.getName());
            }
            spGrid.setItems(mGridList);
            //设置 默认值
            mGridStr = mGridList.get(0);
            //反填默认值
            for (int i = 0;i<mGridList.size();i++){
                String name = mGridList.get(i);
                if (mMyTest.getGrid()!=null && name.equals(mMyTest.getGrid())){
                    //设置 默认值
                    mGridStr = name;
                    //设置 列表默认选中值
                    spGrid.setSelectedIndex(i);
                }
            }
        }

        //站型
        mModelList = CacheManger.getSpinnerKey(mACache, Constant.CACHE_MODEL);
        if (mModelList!=null){
            spStationModel.setItems(mModelList);
            //设置 默认选中值
            mModel = mModelList.get(0);
            for (int i = 0;i<mModelList.size();i++){
                String string = mModelList.get(i);
                if (string.equals(mMyTest.getStationModel())){
                    //设置 反填选中值
                    mModel = string;
                    //设置列表默认选中值
                    spStationModel.setSelectedIndex(i);
                }
            }
        }
        //厂家
        mVenderList = CacheManger.getSpinnerKey(mACache, Constant.CACHE_MANUFACTOR);
        if (mVenderList!=null){
            spVender.setItems(mVenderList);
            //设置 默认选中值
            mVender = mVenderList.get(0);
            for (int i = 0;i<mVenderList.size();i++){
                String string = mVenderList.get(i);
                if (string.equals(mMyTest.getVender())){
                    //设置 反填选中值
                    mVender = string;
                    //设置列表默认选中值
                    spVender.setSelectedIndex(i);
                }
            }
        }
        //区域类型
        mAreaTypeList = CacheManger.getSpinnerKey(mACache, Constant.CACHE_REGION_TYPE);
        if (mAreaTypeList!=null){
            spAreaType.setItems(mAreaTypeList);
            //设置 默认选中值
            mAreaType = mAreaTypeList.get(0);
            for (int i = 0;i<mAreaTypeList.size();i++){
                String string = mAreaTypeList.get(i);
                if (string.equals(mMyTest.getAreaType())){
                    //设置 反填选中值
                    mAreaType = string;
                    //设置列表默认选中值
                    spAreaType.setSelectedIndex(i);
                }
            }
        }
        //主场景类型
        mMainSceneTypeList = CacheManger.getSpinnerKey(mACache, Constant.CACHE_MAIN_TYPE);
        if (mMainSceneTypeList!=null){
            spMainSceneType.setItems(mMainSceneTypeList);
            //设置 默认选中值
            mMainSceneType = mMainSceneTypeList.get(0);
            for (int i = 0;i<mMainSceneTypeList.size();i++){
                String string = mMainSceneTypeList.get(i);
                if (string.equals(mMyTest.getMainSceneType())){
                    //设置 反填选中值
                    mMainSceneType = string;
                    //设置列表默认选中值
                    spMainSceneType.setSelectedIndex(i);
                }
            }
        }

        //优先级
        mPriorityList = CacheManger.getSpinnerKey(mACache, Constant.CACHE_PRIORITY);
        if (mPriorityList!=null){
            spPriority.setItems(mPriorityList);
            //设置 默认选中值
            mPriority = mPriorityList.get(0);
            for (int i = 0;i<mPriorityList.size();i++){
                String string = mPriorityList.get(i);
                if (string.equals(mMyTest.getPriority())){
                    //设置 反填选中值
                    mPriority = string;
                    //设置列表默认选中值
                    spPriority.setSelectedIndex(i);
                }
            }
        }

        //工程期属
        mProjectNumList = CacheManger.getSpinnerKey(mACache, Constant.CACHE_PROJECT_NUMBER);
        if (mProjectNumList!=null){
            spProjectNum.setItems(mProjectNumList);
            //设置 默认选中值
            mProjectNum = mProjectNumList.get(0);
            for (int i = 0;i<mProjectNumList.size();i++){
                String string = mProjectNumList.get(i);
                if (string.equals(mMyTest.getNumOfProject())){
                    //设置 反填选中值
                    mProjectNum = string;
                    //设置列表默认选中值
                    spProjectNum.setSelectedIndex(i);
                }
            }
        }
    }

    /**
     * 获取 我的验收信息图片列表 报错
     */
    @Subscriber(tag = Constant.BUS_WORK_MY_TEST_MSG_IMAGES_ERROR, mode = ThreadMode.MAIN)
    public void initHttpError(String httpError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //销毁弹窗
                mTimeDialog.dismiss();
                //弹出提示
                ToastUtils.showShort(MyTestMsgSubmitActivity.this, Constant.NETWORK_ERROR_MSG);
            }
        }, 1000);
    }

    /**
     * 获取 我的验收信息图片列表
     */
    @Subscriber(tag = Constant.BUS_WORK_MY_TEST_MSG_IMAGES, mode = ThreadMode.MAIN)
    public void initHttpData(final List<ImageJson> list) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //销毁弹窗
                mTimeDialog.dismiss();
                //开始定位
                startLocation();
                if (list != null) {
                    //TODO 图片反填列表
                    mHttpAdapter = new ImageDisplayMagAdapter(MyTestMsgSubmitActivity.this, list,true);
                    //添加 适配器 样式
                    rvHttpImgList.setLayoutManager(new LinearLayoutManager(MyTestMsgSubmitActivity.this, LinearLayoutManager.VERTICAL, false));
                    //添加 适配器
                    rvHttpImgList.setAdapter(mHttpAdapter);
                }
            }
        }, 1000);
    }

    /**
     * 监测 当前手机信号 内部监听类
     */
    private class MyPhoneStateListener extends PhoneStateListener {
        /*得到信号的强度由每个tiome供应商,有更新*/
        final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            //调用超类的该方法，在网络信号变化时得到回答信号
            super.onSignalStrengthsChanged(signalStrength);
            int asu = signalStrength.getGsmSignalStrength();
            String signalInfo = signalStrength.toString();
            String[] params = signalInfo.split(" ");

            //是否 有sim 卡
            boolean isSim = NetUtils.isConnected(MyTestMsgSubmitActivity.this);

            /**
             * 判断 是否有 sim 卡
             */
            if (isSim && !"".equals(mOperator)) {
                if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
                    //4G网络 最佳范围   >-90dBm 越大越好
                    mDbmNumber = Integer.parseInt(params[9]);
                    tvSignal.setText(mOperator + "(4G)" + "，质量：" + mDbmNumber + " dBm");
                } else if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA ||
                        tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
                        tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_EVDO_A ||
                        tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_EVDO_0) {

                    /**
                     *
                     * 解释 上面 判断 中国 联通、电信、   3G常量
                     *
                     * 联通：
                     *      NETWORK_TYPE_HSDPA
                     *      NETWORK_TYPE_UMTS
                     * 电信：
                     *      NETWORK_TYPE_EVDO_A
                     *      NETWORK_TYPE_EVDO_0
                     *
                     * 移动：
                     *      android 没有获取 3g 的方法
                     *
                     */

                    //3G网络最佳范围  >-90dBm  越大越好  ps:中国移动3G获取不到  返回的无效dbm值是正数（85dbm）
                    //在这个范围的已经确定是3G，但不同运营商的3G有不同的获取方法，故在此需做判断 判断运营商与网络类型的工具类在最下方
                    if (mOperator == "中国移动") {
                        mDbmNumber = 0;
                        tvSignal.setText(mOperator + "(3G)" + "，质量：" + "无");
                    } else if (mOperator == "中国联通") {
                        mDbmNumber = signalStrength.getCdmaDbm();
                        tvSignal.setText(mOperator + "(3G)" + "，质量：" + mDbmNumber + " dBm");
                    } else if (mOperator == "中国电信") {
                        mDbmNumber = signalStrength.getEvdoDbm();
                        tvSignal.setText(mOperator + "(3G)" + "，质量：" + mDbmNumber + " dBm");
                    }
                } else {
                    //2G网络最佳范围>-90dBm 越大越好
                    mDbmNumber = -113 + 2 * asu;
                    tvSignal.setText(mOperator + "(2G)" + "，质量：" + mDbmNumber + " dBm");
                }
            } else {
                tvSignal.setText("获取失败，无 SIM 卡");
            }
        }
    }

//    @Override
//    protected void onPause() {
//        // TODO Auto-generated method stub
//        super.onPause();
//        mTel.listen(mMyListener, PhoneStateListener.LISTEN_NONE);
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        mTel.listen(mMyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
//    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        mLocationClient = new AMapLocationClient(this.getApplicationContext());
        mLocationOption = getDefaultOption();
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 设置定位监听
        mLocationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setGpsFirst(true);
        //可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setHttpTimeOut(30000);
        //可选，设置定位间隔。默认为2秒
        mOption.setInterval(2000);
        //可选，设置是否返回逆地理地址信息。默认是true
        mOption.setNeedAddress(true);
        //可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        return mOption;
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        // 设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 启动定位
        mLocationClient.startLocation();
        //显示dialog
        initShowTimeDialog("正在获取定位...",this);
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location && location.getErrorCode() == 0) {
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                String result = location.getAddress();
                mGpsX = location.getLongitude();
                mGpsY = location.getLatitude();
                String lngLat = "经度：" + mGpsX + "   " + "纬度：" + mGpsY;
                //经纬度
                tvGps.setText(lngLat);
            } else {
                //经纬度
                tvGps.setText("经度：获取失败  纬度：获取失败");
                MaterialDialog dialog = new MaterialDialog.Builder(MyTestMsgSubmitActivity.this)
                        .title("定位失败")
                        .content("请检查GPS是否开启，与网络相关设置！")
                        .negativeText("取消")
                        .positiveText("重试")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                //开始重新定位
                                startLocation();
                            }
                        })
                        .show();
                // 设置点击屏幕Dialog不消失
                dialog.setCanceledOnTouchOutside(false);
                //取消Back键监听
                dialog.setCancelable(false);
            }
            //销毁当前获取位置信息 dialog
            mTimeDialog.dismiss();
            //停止定位
            stopLocation();
        }
    };

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        mLocationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationClient = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁定位
        destroyLocation();
    }

    /**
     * 选择事件（全部）
     */
    private void setItemOnClickAll() {
        //TODO 下拉列表
        //省
        spProvince.setOnItemSelectedListener(this);
        //市
        spCity.setOnItemSelectedListener(this);
        //网格
        spGrid.setOnItemSelectedListener(this);
        //厂家
        spVender.setOnItemSelectedListener(this);
        //区域类型
        spAreaType.setOnItemSelectedListener(this);
        //主场景类型
        spMainSceneType.setOnItemSelectedListener(this);
        //站型
        spStationModel.setOnItemSelectedListener(this);
        //优先级
        spPriority.setOnItemSelectedListener(this);
        //工程期属
        spProjectNum.setOnItemSelectedListener(this);
    }

    /**
     * 下拉列表 选择监听事件
     * @param view
     * @param position
     * @param id
     * @param item
     */
    @Override
    public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
        switch (view.getId()){

            case R.id.sp_province:                    //省份
                //设置 选中值
                mProvinceStr = item.toString();
                //设置 省级选择的 子数据 实体
                mProvince = mLinkageList.get(position);
                //省联动事件
                setProvince();
                break;

            case R.id.sp_city:                       //城市
                //设置 选中值
                mCityStr = item.toString();
                //设置 市级选择的 子数据 实体
                mCity = mLinkageCityList.get(position);
                //市联动事件
                setCity();
                break;

            case R.id.sp_grid:                       //网格
                //设置 选中值
                mGridStr = item.toString();
                break;
            case R.id.sp_vender:                     //厂家
                mVender = item.toString();
                break;

            case R.id.sp_area_type:                 //区域类型
                mAreaType = item.toString();
                break;

            case R.id.sp_main_scene_type:           //主场景类型
                mMainSceneType = item.toString();
                break;

            case R.id.sp_station_model:             //站型
                mModel = item.toString();
                break;

            case R.id.sp_priority:                  //优先级
                mPriority = item.toString();
                break;

            case R.id.sp_project_num:               //工程期属
                mProjectNum = item.toString();
                break;
        }
    }

    /**
     * 省级点击联动事件
     */
    private void setProvince(){
        //联动 市级列表
        mLinkageCityList = mProvince.getChildrenNodes();
        if (mLinkageCityList != null) {
            mCityList.clear();
            //循环获取name
            for (Linkage province : mLinkageCityList){
                mCityList.add(province.getName());
            }
            //数据填充
            spCity.setItems(mCityList);
            //设置市级 默认选中值
            mCityStr = mCityList.get(0);
            //设置 下拉列表最大高度
            if (mCityList.size() > 0)
                spCity.setDropdownMaxHeight(1000);
        }
    }

    /**
     * 市级点击联动事件
     */
    private void setCity(){
        //联动 区级列表
        mLinkageGridList = mCity.getChildrenNodes();
        if (mLinkageGridList != null) {
            mGridList.clear();
            //循环获取name
            for (Linkage province : mLinkageGridList){
                mGridList.add(province.getName());
            }
            spGrid.setItems(mGridList);
            //设置区级 默认选中值
            mGridStr = mGridList.get(0);
            //设置 下拉列表最大高度
            if (mGridList.size() > 0)
                spGrid.setDropdownMaxHeight(1000);
        }
    }

    /**
     * 按钮点击事件
     * @return
     */
    @OnClick({R.id.iv_return,R.id.layout_add_list,R.id.btn_submit,
            R.id.iv_relocation,R.id.iv_dbm_push})
    public void onClick(View view){
        switch (view.getId()){

            case R.id.iv_return:         //返回
                finish();
                break;

            case R.id.layout_add_list:   //分组添加事件
                ImageMag imageMag = new ImageMag();
                imageMag.setName("");
                imageMag.setHttpImgList(new ArrayList<String>());
                imageMag.setLocalImgList(new ArrayList<String>());

                //上传图片Flag 初始化 （true：当前位置可以继续上传，false：当前位置不可以上传了）
                List<Boolean> mHttpImgFlag = new ArrayList<>();
                for(int i = 0;i < Constant.MAX_SELECT_PIC_NUM;i++){
                    mHttpImgFlag.add(i,true);
                }
                imageMag.setHttpImgFlag(mHttpImgFlag);
                //添加一个 item
                mUploadAdapter.addItem(mImageList.size(),imageMag);
                break;

            case R.id.btn_submit:         //提交按钮
                setDataSubmit();
                break;

            case R.id.iv_relocation:     //重新定位
                //开始重新定位
                startLocation();
                break;

            case R.id.iv_dbm_push:       //刷新 dbm
                //设置监听器监听特定事件的状态
                mTel.listen(mMyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
                break;
        }
    }

    /**
     * 数据提交
     */
    private void setDataSubmit() {

        //物理站名称
        String name = etPhysicalName.getText().toString();
        //物理站地址
        String address = etPhysicalAddress.getText().toString();
        //手动输入的 经度
        String mMyGpsX = etMyGpsX.getText().toString();
        //手动输入的 纬度
        String mMyGpsY = etMyGpsY.getText().toString();

        //图片上传 json
        List<ImageJson> list = mUploadAdapter.getUploadImgList();
        //添加 新上传图片的数据
        list.addAll(mHttpAdapter.getHttpImgList());
        //将 list 转换成 json 字符串
        String imgJson = new Gson().toJson(list).toString();

        //定义一个 检索 图片分组名是否为空的 flag
        boolean imgUploadFlag = false;
        for (ImageJson img : list){
            if (img.getImgCategorys().equals("")){
                imgUploadFlag = false;
                break;
            }else{
                imgUploadFlag = true;
            }
        }

        /**
         * 逻辑判断
         */
        if (list.size()!=0 && !imgUploadFlag){
            ToastUtils.showShort(this,"还有组名没有填写！");
        }else if ("".equals(name)){
            ToastUtils.showShort(this,"请填写物理基站名称！");
        }else if ("".equals(address)){
            ToastUtils.showShort(this,"请填写物理基站地址！");
        }else{
            //网络请求 提交
            initShowTimeDialog("正在提交验收信息，请稍后....", this);
            mApiManager.workMyTestMsgSubmit(mUser.getId(),mMyTest.getId(),mMyTest.getBaseStationId(),mProvinceStr,mCityStr,mGridStr,
                    mVender,name,address,mAreaType,mMainSceneType,mModel,mMyGpsX,mMyGpsY,mGpsX+"",mGpsY+"", "",
                    mUser.getDepartment(),mMyTest.getNameOfOpenStationAddr(),mProjectNum,imgJson,mPriority,mDbmNumber+"");
        }
    }


    /**
     * 我的验收信息提交 提交网络请求 解析报错
     */
    @Subscriber(tag = Constant.BUS_WORK_MY_TEST_MSG_SUBMIT_ERROR, mode = ThreadMode.MAIN)
    public void initHttpSubmitError(String strError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏dialog
                mTimeDialog.dismiss();
                //弹出相应的提示
                ToastUtils.showShort(MyTestMsgSubmitActivity.this,Constant.NETWORK_ERROR_MSG);
            }
        }, 1000);
    }

    /**
     *  我的验收信息提交 提交网络请求 数据返回成功
     */
    @Subscriber(tag = Constant.BUS_WORK_MY_TEST_MSG_SUBMIT, mode = ThreadMode.MAIN)
    public void initHttpSubmitData(final State state) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏dialog
                mTimeDialog.dismiss();

                //TODO 网络请求业务逻辑判断
                if (state.getState().equals("1")) {
                    mMsgDialog = new DialogUtils() {
                        @Override
                        public void onNegativeClick() {
                        }
                        @Override
                        public void onPositiveClick() {
                            //通知刷新 基站数据列表
                            EventBus.getDefault().post("WorkPush",Constant.BUS_WORK_PUSH);
                            //销毁当前页面
                            finish();
                        }
                    };
                    mMsgDialog.showMsgDialog(MyTestMsgSubmitActivity.this,"验收成功",
                            "当前基站信息已验收成功！","好的，知道了");
                }else{
                    ToastUtils.showShort(MyTestMsgSubmitActivity.this,state.getMsg());
                }

            }
        }, 1000);
    }

    /**
     * 图片处理返回页面
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //TODO 选择之后的 图片 url 返回
        if (requestCode == Constant.REQUEST_CAMERA_PHOTO) {
            /**
             * 1.是否已经点击确认了
             * 2.获取返回 的 url 集合
             * 3.开始进行 图片压缩
             * 4.根据压缩后的 图片路径 进行填充到 图片集合
             * 5.刷新 adapter 数据
             */
            if (resultCode == Activity.RESULT_OK) {
                //TODO 获取当前图片路径 转成 URi的形式
                List<String> mSelected = Matisse.obtainPathResult(data);
                //TODO 开始图片压缩
                Biscuit.with(this)
                        .path(mSelected)
                        .listener(new OnCompressCompletedListener() { //压缩监听
                            @Override
                            public void onCompressCompleted(CompressResult compressResult) {
                                //TODO 本地图片
                                //获取图片 返回 的压缩 后的路径
                                List<String> urls = compressResult.mSuccessPaths;
                                //获取现在 真正的 数据集合
                                mImageList = mUploadAdapter.getImageMags();
                                //添加到图片集合里面去
                                mImageList.get(mPos).getLocalImgList().addAll(urls);
                                //图片选择回调 列表刷新
                                mUploadAdapter.notifyDataSetChanged();

                                //TODO 网络图片
                                //获取集合
                                List<String> httpImg = mImageList.get(mPos).getAdapter().getHttpUrls();
                                //填充到数据结合中
                                List<String> imgs = mImageList.get(mPos).getHttpImgList();
                                imgs.addAll(httpImg);
                                imgs = StringUtils.removeDuplicate(imgs);

                                mImageList.get(mPos).getHttpImgList().clear();
                                mImageList.get(mPos).getHttpImgList().addAll(imgs);
                                //图片选择回调 列表刷新
                                mUploadAdapter.notifyDataSetChanged();
                            }
                        })
                        .ignoreLessThan(100)//忽略小于100kb的图片不压缩，返回原图路径
                        .build()            //开始执行
                        .asyncCompress();   //异步压缩
            }
        }
    }

}
